<?php

namespace app\api\services\admin\setting;

use app\api\common\service\BaseServices;
use app\api\common\traits\ServicesTrait;
use app\api\dao\admin\setting\DictDao;
use think\Exception;

class DictServices extends BaseServices
{
    use ServicesTrait;

    public function __construct(DictDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * @param array $where
     *
     * @return array
     * @throws \ReflectionException
     */
    public function select(array $where): array
    {
        [$page, $limit] = $this->getPageValue();
        $list  = $this->dao->selectList($where, '*', $page, $limit, 'id ASC', [], true)->toArray();
        $count = $this->dao->count($where);
        return compact('list', 'count');
    }

    /**
     * @param array $data
     *
     * @return mixed
     * @throws \think\Exception
     */
    public function insert(array $data): mixed
    {
        $list = $this->dao->get(['name' => $data['name']], ['name,id']);
        if (!empty($list)) {
            throw new Exception('字典已经存在');
        }
        $data['value'] = json_encode($data['value']);
        return $this->dao->save($data);
    }

    /**
     * @param string|int|array $id
     * @param array            $data
     * @param string           $key
     *
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(string|int|array $id, array $data, string $key = 'name'): mixed
    {
        $list = $this->dao->get(['name' => $data['name'], ['delete_time', '=', null]], ['name,id']);
        if (empty($list)) {
            throw new Exception('字典不存在');
        }
        $data['value'] = json_encode($data['value']);
        return $this->dao->update($id, $data, $key);
    }
}
